<template>
  <div>
    <Dialog
      ref="examineDialogRef"
      :allDeptList="allDeptList"
      :status="0"
      :btn1="'确认'"
      :btn2="'取消'"
      summary="请确认是否将订单撤回上一步"
      title="订单撤回确认"
      @handelOK="toBatchExamine" />
    <Dialog
      ref="submitDialogRef"
      :allDeptList="allDeptList"
      :summary="submitSummary"
      :btn1="'确认提交'"
      :btn2="'暂不提交'"
      title="订单提交确认"
      @handelOK="submitCost" />
    <Dialog
      ref="publishDialogRef"
      :allDeptList="allDeptList"
      :btn1="'确认提交'"
      :btn2="'暂不提交'"
      :summary="'请确认是否发布订单'"
      tip="接收人请选择需要审批的人员：如销售经理"
      title="订单发布确认"
      @handelOK="toPublish" />
    <Dialog
      ref="backDialogRef"
      :allDeptList="allDeptList"
      :btn1="'确认'"
      :btn2="'取消'"
      :summary="summary"
      title="订单撤回确认"
      @handelOK="revoke" />
  </div>
</template>

<script>
import { examineOrder, submitCost, publishOrder, backOrder } from '@/api/order';
import { allDeptlist } from '@/api/select';
import Dialog from '@/components/CreateOrder/orderDetail/dialog';
import { handelDepartmentData } from '@/utils';
import { mapState } from 'vuex';

import { showModal } from '@/utils/message';
import { MessageBox } from 'element-ui';
import ElMessage from '@/utils/message';
export default {
  components: { Dialog },
  props: {
    allDefaultDept: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      allDeptList: [],
      ids: '',
      submitSummary: '',
      summary: '',
      orderStatus: null
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  destroyed() {
    this.ids = '';
  },
  created() {
    if (this.allDefaultDept) {
      this.allDeptList = this.allDefaultDept;
    } else {
      this.getAllDeptList();
    }
  },
  methods: {
    batchExamine(ids, defaultUser = []) {
      this.ids = ids;
      const h = this.$createElement;
      const showMobilePage = this.showMobilePage;
      const handelOk = () => {
        MessageBox.close();
        const receiveUsers = defaultUser.map(i => i.id);
        this.toBatchExamine({
          ids: ids,
          status: 1,
          receiveUsers: receiveUsers,
          isSendMsg: true,
          dingTalkMsg: '恭喜，您的订单已通过审批！',
          // url: `${location.origin}?redirect=${this.$route.path}`
          url: `${location.origin}?redirect=/orderPage/orderdetail/`
        });
      };
      const rejectFun = () => {
        MessageBox.close();
        if (this.$refs.examineDialogRef) {
          this.$refs.examineDialogRef.showDialog({
            defaultMsg: '您有被退回待发布的订单，请及时处理',
            defaultObjectUser: defaultUser,
            receiveDisabled: true,
            extendParams: { url: `${location.origin}?redirect=/orderPage/orderdetail/` }
          });
        }
      };
      let msg = '请确认是否通过该订单审批？';
      if (ids && typeof ids === 'string' && ids.split(',').length > 1) {
        msg = '请确认批量通过审批吗？';
      }
      MessageBox.confirm('', '', {
        message: h('p', null, [
          h('div', null, msg),
          h('div', { class: 'btns-container' }, [
            h('el-button', { on: { click: handelOk }, class: 'resolve-btn', props: { type: 'primary' }}, '通过 '),
            h('el-button', { on: { click: rejectFun }, class: 'reject-btn' }, '拒绝 '),
            h('el-button', { on: { click: MessageBox.close }, class: 'cancel-btn' }, '暂不审批')
          ])
        ]),
        confirmButtonText: '通过',
        cancelButtonText: '拒绝',
        showClose: false,
        showCancelButton: false,
        showConfirmButton: false,
        type: 'warning',
        lockScroll: false,
        customClass: `del-message del-message-cancel message-box-order ${showMobilePage ? ' mobile-message' : ''}`,
        iconClass: 'del-icon',
        center: true
      });
    },
    toBatchExamine(data = {}) {
      // status: 1: 通过审批 0:审批不通过
      data.ids = this.ids;
      if (data.receiveUsers instanceof Array) {
        data.receiveUsers = data.receiveUsers.join(',');
      }
      this.$emit('setLoading', '审批中');
      examineOrder(data).then(res => {
        this.$emit('setLoading', false);
        if (res.code === 200) {
          ElMessage.success('审批成功');
          this.$emit('fetchData');
          this.$emit('clearMixinSelection');
        } else {
          ElMessage.success(res.message);
        }
      }).catch(() => {
        this.$emit('setLoading', false);
      });
    },
    submitCost(data = {}) {
      data.auditorId = data.receiveUsers;
      submitCost(data).then(res => {
        if (res.code === 200) {
          ElMessage.success('提交成功');
          this.$emit('fetchData');
          this.$emit('clearMixinSelection');
        } else {
          ElMessage.success(res.message);
        }
      });
    },
    batchPublish(ids, defaultUser = []) {
      this.$refs.publishDialogRef.showDialog({ defaultMsg: '您有新待审批订单需要处理', isSubmitCost: false, defaultObjectUser: defaultUser, extendParams: { id: ids }});
    },
    toPublish(data = {}) {
      publishOrder(data).then(res => {
        if (res.code === 200) {
          if (res.data && res.data.ids) {
            showModal('所提交订单中存在</br>未采集或未上传截图的订单', '', {
              center: true,
              showClose: true,
              confirmButtonText: '仅发布有截图订单',
              cancelButtonText: '取消发布',
              customClass: 'public-btn del-message del-message-cancel'
            }).then(() => {
              const ids = Array.isArray(res.data.ids) && res.data.ids.length ? res.data.ids.join() : res.data.ids;
              data.id = ids;
              this.toPublish(data);
            });
          } else {
            ElMessage.success('提交成功');
            this.$emit('fetchData');
            this.$emit('clearMixinSelection');
          }
        } else {
          ElMessage.success(res.message);
        }
      });
    },
    batchBack(ids, defaultUser = [], defaultMsg, summary, orderStatus, isSeal) {
      this.summary = summary;
      this.orderStatus = orderStatus;
      let status = orderStatus - 1;
      // v2.8.8 取消待核算步骤（2）
      // else if (this.orderStatus === 2) {
      //   status = 1;
      // }

      if (this.orderStatus === 1) {
        status = 0;
      } else if (this.orderStatus === 3) {
        status = 1;
      } else if (this.orderStatus === 4) {
        status = 3;
      }
      const extendParams = {
        id: ids,
        status: status,
        currentStatus: orderStatus
      };
      this.$refs.backDialogRef.showDialog({ defaultMsg, defaultObjectUser: defaultUser, isSubmitCost: false, extendParams: extendParams, isSeal });
    },
    revoke(data) {
      this.$emit('setLoading', '撤回中');
      backOrder(data).then(res => {
        this.$emit('setLoading', false);
        if (res.code === 200) {
          ElMessage.success('撤回成功');
          this.$emit('fetchData');
          this.$emit('clearMixinSelection');
        } else {
          ElMessage.success(res.message);
        }
      }).catch(() => {
        this.$emit('setLoading', false);
      });
    },
    getAllDeptList() {
      allDeptlist().then(res => {
        handelDepartmentData(res.data);
        this.allDeptList = res.data;
      });
    }
  }
};
</script>

<style lang="scss">
.public-btn .el-button--default:first-child {
  margin-right: -236px !important;
}
.public-btn {
  .el-message-box__btns {
    padding-left: 80px !important;
  }
}
.message-box-order {
  .el-message-box__btns {
    display: none;
  }
  .el-message-box__content {
    padding-bottom: 0;
    padding-top: 20px;
  }
  .btns-container {
    margin-top: 40px;
    .resolve-btn {
      width: 120px;
      padding: 7px 0;
      background: #406EFF;
      border-radius: 4px;
      font-size: 16px;
      font-weight: 500;
      color: #FFFFFF;
    }
    .reject-btn {
      width: 80px;
      padding: 7px 0;
      font-size: 16px;
      font-weight: 500;
      border-color: #FDF3ED;
      background: #FDF3ED;
      color: #FD8546;
    }
    .cancel-btn {
      width: 80px;
      padding: 7px 0;
      font-size: 16px;
      font-weight: 500;
      border-color: #EFF3FB;
      background: #EFF3FB;
      color: #406EFF;
    }
  }
  &.mobile-message {
    .resolve-btn {
      width: 80px;
    }
  }
}

</style>

